<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑考试' : '创建考试'"
    width="60%"
    :before-close="handleClose"
    class="form-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="exam-form">

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入考试标题"></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入考试描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="考试日期" prop="exam_date">
        <el-date-picker
          v-model="form.exam_date"
          type="datetime"
          placeholder="选择考试日期"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="教室" prop="classroom">
        <el-input v-model="form.classroom" placeholder="请输入考试教室"></el-input>
      </el-form-item>

      <el-form-item label="座位类型" prop="seating_type">
        <el-input v-model="form.seating_type" placeholder="请输入座位类型"></el-input>
      </el-form-item>

 <el-form-item label="考试附件">
    <!-- 显示现有的考试附件 -->
    <div v-if="isEdit && examAttachments && examAttachments.length > 0" class="existing-attachments">
      <h4>现有附件：</h4>
      <el-card shadow="never" class="attachment-list">
        <div v-for="attachment in examAttachments"
             :key="attachment.id"
             class="attachment-item">
          <el-link
            :href="attachment.file_path"
            type="primary"
            target="_blank">
            <el-icon class="document-icon"><Document /></el-icon>
            {{ getFileName(attachment.file_path) }}
          </el-link>
        </div>
      </el-card>
    </div>

    <!-- 上传新附件 -->
    <div class="upload-section">
      <div v-if="isEdit" class="upload-hint">上传新附件（不会影响现有附件）：</div>
      <el-upload
        class="exam-upload"
        :auto-upload="false"
        :file-list="fileList"
        multiple
        :before-upload="validateFile"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove">
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持常见文档格式，单个文件不超过10MB
          </div>
        </template>
      </el-upload>
    </div>
  </el-form-item>

  <el-form-item label="答案附件">
    <!-- 显示现有的答案附件 -->
    <div v-if="isEdit && answerAttachments && answerAttachments.length > 0" class="existing-attachments">
      <h4>现有答案附件：</h4>
      <el-card shadow="never" class="attachment-list">
        <div v-for="attachment in answerAttachments"
             :key="attachment.id"
             class="attachment-item">
          <el-link
            :href="attachment.file_path"
            type="danger"
            target="_blank">
            <el-icon class="document-icon"><Document /></el-icon>
            {{ getFileName(attachment.file_path) }}
          </el-link>
        </div>
      </el-card>
    </div>

    <!-- 上传新答案附件 -->
    <div class="upload-section">
      <div v-if="isEdit" class="upload-hint">上传新答案附件（不会影响现有附件）：</div>
      <el-upload
        class="exam-answer-upload"
        :auto-upload="false"
        :file-list="answerFileList"
        multiple
        :before-upload="validateFile"
        :on-change="handleAnswerFileChange"
        :on-remove="handleAnswerFileRemove">
        <el-button type="primary">选择答案文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持常见文档格式，单个文件不超过10MB
          </div>
        </template>
      </el-upload>
    </div>
  </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  form: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  fileList: {
    type: Array,
    default: () => []
  },
  answerFileList: {
    type: Array,
    default: () => []
  },
    examAttachments: {
    type: Array,
    default: () => []
  },
  answerAttachments: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits([
  'update:visible',
  'update:form',
  'update:fileList',
  'update:answerFileList',
  'submit'
])

// 添加文件名获取函数
const getFileName = (path) => {
  if (!path) return ''
  const decodedPath = decodeURIComponent(path)
  return decodedPath.split('/').pop()
}

const formRef = ref(null)
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入考试标题', trigger: 'blur' }
  ],
  exam_date: [
    { required: true, message: '请选择考试日期', trigger: 'change' }
  ],
  classroom: [
    { required: true, message: '请输入考试教室', trigger: 'blur' }
  ]
}

const validateFile = (file) => {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type);
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    ElMessage.error('只能上传PDF或Word文档!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  return true;
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁止选择今天之前的日期
}

const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('update:visible', false)
}

const handleFileChange = (file, fileList) => {
  emit('update:fileList', fileList)
}

const handleFileRemove = (file, fileList) => {
  emit('update:fileList', fileList)
}

const handleAnswerFileChange = (file, fileList) => {
  emit('update:answerFileList', fileList)
}

const handleAnswerFileRemove = (file, fileList) => {
  emit('update:answerFileList', fileList)
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      emit('submit')
    } else {
      console.error('表单验证失败:', fields)
    }
  })
}
</script>

<style scoped>
.form-dialog {
  .el-dialog__body {
    padding: 20px 20px 0;
  }
}

.exam-form {
  padding: 20px;
}

.exam-upload, .exam-answer-upload {
  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
}
</style>